package com.example.myfirstapp;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

@TargetApi(8)
public class MainActivity extends Activity {
	
	Facebook facebook = new Facebook("483686181663831");
	private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
	private String msgClicked = "";
	private boolean isHide = false;
	private int count = 0;
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//				StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//		StrictMode.setThreadPolicy(policy);
		final Button butObj = (Button) findViewById(R.id.button1);
		System.out.println(butObj);
//		butObj.getBackground().setColorFilter(0xFFFF0000,
//				PorterDuff.Mode.MULTIPLY);
//		butObj.setBackgroundColor(Color.BLUE);
		
		
		TextView textview = (TextView) findViewById(R.id.textLayout3);
		SpannableString str = SpannableString.valueOf("Feel Cube");
		str.setSpan(new URLSpan(""), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		textview.append(str);  
		textview.setOnClickListener(mCorkyListener);

		textview = (TextView) findViewById(R.id.textLayout4);
		str = SpannableString.valueOf("Feel Cube");
		str.setSpan(new URLSpan(""), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		textview.append(str);  
		textview.setOnClickListener(mCorkyListener);

		textview = (TextView) findViewById(R.id.textLayout1);
		str = SpannableString.valueOf("Senthil Kumar Rajendren");
		str.setSpan(new URLSpan(""), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		textview.append(str);  
		textview.setOnClickListener(textListener2);

		textview = (TextView) findViewById(R.id.textLayout2);
		str = SpannableString.valueOf("Senthil Kumar Rajendren");
		str.setSpan(new URLSpan(""), 0, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		textview.append(str);  
		textview.setOnClickListener(textListener2);
		
		ImageView imgview = (ImageView) findViewById(R.id.imageLayout3);		
	    Drawable image = ImageOperations(this, "http://graph.facebook.com/100001226784240/picture", "image.jpg");
		imgview.setImageDrawable(image);
		
		imgview = (ImageView) findViewById(R.id.imageLayout2);		
	    image = ImageOperations(this, "http://profile.ak.fbcdn.net/hprofile-ak-ash4/370759_1631763960_433554416_q.jpg", "image.jpg");
		imgview.setImageDrawable(image);
		
		imgview = (ImageView) findViewById(R.id.imageLayout1);		
	    image = ImageOperations(this, "http://profile.ak.fbcdn.net/hprofile-ak-ash4/370759_1631763960_433554416_q.jpg", "image.jpg");
		imgview.setImageDrawable(image);
		
		imgview = (ImageView) findViewById(R.id.imageLayout4);		
	    image = ImageOperations(this, "http://graph.facebook.com/100001226784240/picture", "image.jpg");
		imgview.setImageDrawable(image);
		
		textview = (TextView) findViewById(R.id.fbs1);
		textview.setOnClickListener(fbWallPostListener);
		textview = (TextView) findViewById(R.id.fbs2);
		textview.setOnClickListener(fbWallPostListener);
		textview = (TextView) findViewById(R.id.fbs3);
		textview.setOnClickListener(fbWallPostListener);
		textview = (TextView) findViewById(R.id.fbs4);
		textview.setOnClickListener(fbWallPostListener);
		
		
	}
	 @Override
	protected void onStart() {
		 Log.d(this.getClass().getName(),"inside onstart");
		 facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener(){
//		 facebook.authorize(this, new DialogListener() {
	            @Override
	            public void onComplete(Bundle values) {	
	            	MyCounter timer = new MyCounter(300000,1000);
	            	timer.start();
			    }

	            @Override
	            public void onFacebookError(FacebookError error) {}

	            @Override
	            public void onError(DialogError e) {}

	            @Override
	            public void onCancel() {}
	    });
		Log.d(this.getClass().getName(), "seeing facebook status::::"+facebook.isSessionValid());
			/*if(facebook.isSessionValid()){
				Log.d(this.getClass().getName(), "exit facebook");
				// get information about the currently logged in user
				mAsyncRunner.request("yourPage", new RequestListener() {

				    @Override
				    public void onComplete(String response, Object state) {
				        Log.d(this.getClass().getName(), response);   // page info JSONObject

					}

				    @Override
				    public void onIOException(IOException e, Object state) {}

				    @Override
				    public void onFileNotFoundException(FileNotFoundException e,
				            Object state) { }

				    @Override
				    public void onMalformedURLException(MalformedURLException e,
				            Object state) { }

				    @Override
				    public void onFacebookError(FacebookError e, Object state) { }

				});
			}*/
/*		Timer timer1 = new Timer(); 
		timer1.schedule(new TimerTask(){
			@Override
			public void run() {
				Hide();
//				try {
////					this.wait(2000);
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				show();
			}
			
		}, 0, 10000);*/
		super.onStart();
	}
	private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
	        try {
	            InputStream is = (InputStream) this.fetch(url);
	            Drawable d = Drawable.createFromStream(is, "src");
	            return d;
	        } catch (MalformedURLException e) {
	            return null;
	        } catch (IOException e) {
	            return null;
	        }
	    }

	public Object fetch(String address) throws IOException {
        URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void submitBut(View button) {
		Log.d(this.getClass().getName(), "inside submitBut");
		Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
		startActivity(mainIntent);
		finish();
		Log.d(this.getClass().getName(), "exit submitBut");
	}

	private OnClickListener mCorkyListener = new OnClickListener() {
		public void onClick(View v) {
			/*
			 * AlertDialog.Builder ad = new
			 * AlertDialog.Builder(MainActivity.this); ad.setTitle("Argh");
			 * ad.setMessage("Watch out!"); ad.setCancelable(false);
			 * ad.setNeutralButton("Close", new
			 * DialogInterface.OnClickListener() { public void
			 * onClick(DialogInterface dialog,int id) { // if this button is
			 * clicked, just close // the dialog box and do nothing
			 * dialog.cancel(); }}).show(); // do something when the button is
			 * clicked
			 */Log.d(this.getClass().getName(), "inside listener");
			 String url = "https://facebook.com/feelcube";
			 Intent i = new Intent(Intent.ACTION_VIEW);
			 Uri u = Uri.parse(url);
			 i.setData(u);
			 startActivity(i);

		}
	};
	
	private OnClickListener textListener2 = new OnClickListener() {
		public void onClick(View v) {
			Log.d(this.getClass().getName(), "inside listener");
			 String url = "https://facebook.com/1631763960";
			 Intent i = new Intent(Intent.ACTION_VIEW);
			 Uri u = Uri.parse(url);
			 i.setData(u);
			 startActivity(i);

		}
	};
	
	private OnClickListener fbWallPostListener = new OnClickListener() {
		public void onClick(View v) {
			
			Log.d(this.getClass().getName(), "Inside fbWallPostListener"+v.getTag());
			String facebookMessage = (String)v.getTag();
			if (facebookMessage == null){
				facebookMessage = "Test wall post";
			}
			Bundle parameters = new Bundle();
            parameters.putString("message", facebookMessage);
            parameters.putString("description", "topic share");
            parameters.putString("link", "http://billiontalks.com");
            parameters.putString(Facebook.TOKEN,"363474a49987539ce7a6c2e622ca42");  
            if (! facebook.isSessionValid()) {
            	Log.d(this.getClass().getName(),"session not valid");
    			loginAndPostToWall();
    		}
            try {
            	Log.d(this.getClass().getName(),"session valid");
    	        facebook.request("me");
				String response = facebook.request("me/feed", parameters, "POST");
				Log.d("Tests", "got response: " + response);
				if (response == null || response.equals("") ||
				        response.equals("false")) {
					showToast("Blank response.");
				}
				else {
					showToast("Message posted to your facebook wall!");
				}
//				finish();
			} catch (Exception e) {
				showToast("Failed to post to wall!");
				e.printStackTrace();
				finish();
			}

		}
	};
	private static final String[] PERMISSIONS = new String[] {"publish_stream"};
	public void loginAndPostToWall(){
		 facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
	}
	
	class LoginDialogListener implements DialogListener {
	    public void onComplete(Bundle values) {
	    	saveCredentials(facebook);
		}	    
	    public void onFacebookError(FacebookError error) {
	    	Log.d("facebookeror","Authentication with Facebook failed!");
//	        finish();
	    }
	    public void onError(DialogError error) {
	    	Log.d("facebookeror","Authentication with Facebook failed!");
//	        finish();
	    }
	    public void onCancel() {
	    	Log.d("facebookeror","Authentication with Facebook cancelled!");
//	        finish();
	    }
	}

	public boolean saveCredentials(Facebook facebook) {
    	Editor editor = getApplicationContext().getSharedPreferences("facebook-credentials", Context.MODE_PRIVATE).edit();
    	editor.putString("access_token", facebook.getAccessToken());
    	editor.putLong("expires_in", facebook.getAccessExpires());
    	return editor.commit();
	}
	private void showToast(String message){
//		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
	}
	public class MyCounter extends CountDownTimer{
		 
        public MyCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
 
        @Override
        public void onFinish() {
            System.out.println("Timer Completed.");
            
        }
 
        @Override
        public void onTick(long millisUntilFinished) {

        		Log.d("timer","Inside time hide");
        		int viewId = 0;
        		Random ranum = new Random();
        		int num = ranum.nextInt();
        		if(isHide){
        			num = count;
        		}
        		if(num <0){
        			num *=-1;
        		}
        		Log.d("timer", "Value of num:::"+num);
        		Log.d("timer", "Value of num:::"+num%4);
        		if(num%4 == 0){
        			viewId = R.id.frameLayout1;
        		}else if(num%4 == 1){
        			viewId = R.id.frameLayout2;
        		}else if(num%4 == 2){
        			viewId = R.id.frameLayout3;
        		}else if(num%4 == 3){
        			viewId = R.id.frameLayout4;
        		}
        		RelativeLayout rl = (RelativeLayout) findViewById(viewId);
        		if(isHide){
        			rl.setVisibility(View.VISIBLE);
        			isHide = false;
        		}else{
        			rl.setVisibility(View.GONE);
        			isHide = true;
        			count = num%4;
        		}
        		
        		Log.d("timer","Exit time show");
        }
    }

}
